import React from 'react';
import { connect } from 'dva';
import { Icon, Modal } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import styles from './ExamPaperListPage.less';
import { Helmet } from 'react-helmet';
import Container from '../components/Base/Container';
import { examEndCheck } from "../services/examService";

const _ = require('lodash');


class ExamPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectKey: '',
    };
  }

  componentDidMount() {
    this.props.fetchExamLibList();

    const shopId = this.props.location.query.shopId;
    window.addEventListener("hashchange", (e) => {
      const o = e.oldURL;
      const n = e.newURL;

      if (_.includes(o, 'examReasult') && _.includes(n, 'examMain')) {
        // window.history.pushState({ title: "门店考试", url: "/#/examPaperList?shopId=" + shopId }, "门店考试", "/#/examPaperList?shopId=" + shopId);
        window.history.forward();
      }
    });
  }

  render() {
    let { dispatch, shopId, examLibName, examPaperList } = this.props;
    examPaperList = _.filter(examPaperList, (v) => {
      const endTime = v.expiry_date && v.expiry_date.length > 0 && v.expiry_date[1] ? v.expiry_date[1] : null;
      return (endTime && moment(endTime).endOf('day').isAfter(moment()));// 只展示没结束的
    });

    return (
      <Container title={shopId ? '门店考试' : examLibName + '考试'}>
        <Helmet>
          <title>
            {shopId ? '门店考试' : examLibName + '考试'}
          </title>
        </Helmet>

        <div className={styles.head}>请选择试卷</div>
        <div className={styles.line} />

        {
          examPaperList.length > 0 &&
          examPaperList.map((item, index) => (
            <div
              onClick={() => {
                const { phone, shopId } = this.props.user;
                const type = 'exam';
                const ref_type = item.ref_type;
                const ref_id = item._id;
                const expiryDate = item.expiry_date;


                if (ref_type === 'examPaper') {
                  this.props.goToExam(item);
                } else {
                  // 检测考试时候开始,时候结束
                  if (expiryDate && expiryDate.length === 2) {
                    const startTime = expiryDate[0];
                    const endTime = expiryDate[1];
                    console.log(moment(startTime).startOf('day'), moment(endTime).endOf('day'));
                    if (startTime && moment().isBefore(moment(startTime).startOf('day'))) {
                      Modal.alert('提示', '考试还没开始！', [
                        { text: '确定', onPress: () => {} },
                      ]);
                      return;
                    }
                    if (endTime && moment().isAfter(moment(endTime).endOf('day'))) {
                      Modal.alert('提示', '考试已结束！', [
                        { text: '确定', onPress: () => {} },
                      ]);
                      return;
                    }
                  }

                  examEndCheck({ phone, shopId, type, ref_type, ref_id })
                    .then((body) => {
                      if (body && body.data && body.data.status) {
                        Modal.alert('提示', '本次试卷您已考过，无法再次参加！', [
                          { text: '确定', onPress: () => {} },
                        ]);
                      } else {
                        Modal.alert('提示', '本次试卷每人限考1次，是否进入考试？', [
                          {
                            text: '不进入',
                            onPress: () => {
                            },
                          },
                          { text: '进入', onPress: () => this.props.goToExam(item) },
                        ]);
                      }
                    }, (error) => {
                      console.log(error);
                    });
                }
              }}
              key={index}
              className={styles.section}
            >
              <div className={styles.section1}>
                <div className={styles.section11}>
                  <div className={styles.name}>
                    <img src={require('../assets/examCircle.png')} alt="" />
                    {item.name}
                  </div>
                  <div className={styles.desc}>
                    {item.desc}
                  </div>
                  <div className={styles.date}>
                    试卷有效期至{moment(item.expiry_date[1]).format('YYYY年MM月DD日')}
                  </div>

                </div>
                <div>
                  <Icon type="right" />
                </div>
              </div>

              <div className={styles.section2}>
                <div className={styles.section21}>
                  <div>考试时间</div>
                  <div>{item.exam_time}分钟</div>
                </div>
                <div className={styles.section21}>
                  <div>单选题</div>
                  <div>{item.radio_num}题 | 每题{item.radio_per_score}分</div>

                </div>
                <div className={styles.section21}>
                  <div>多选题</div>
                  <div>{item.checkbox_num}题 | 每题{item.checkbox_per_score}分</div>
                </div>

              </div>
            </div>
          ))
        }

        {
          examPaperList.length === 0 &&
          <div className={styles.section4}>
            <img src={require('../assets/examCircle.png')} alt="" />
            暂无可用的试卷
          </div>
        }

      </Container>
    );
  }
}


export default connect(
  (state, props) => {
    const ref_type = props.location.query.ref_type;
    const ref_id = props.location.query.ref_id;
    const shopId = props.location.query.shopId;
    const examLibName = decodeURIComponent(props.location.query.examLibName);
    return {
      ref_type,
      ref_id,
      shopId,
      examLibName,
      examPaperList: state.exam.examPaperList,
      user: state.auth.currentUser,
    };
  },
  (dispatch, props) => {
    return {
      fetchExamLibList() {
        const ref_type = props.location.query.ref_type;
        const ref_id = props.location.query.ref_id;
        const shopId = props.location.query.shopId;
        if (shopId) {
          dispatch({ type: 'exam/fetchExamPaperList', payload: { filter: { ref_type: 'shopExamPaper', shopId } } });
        } else {
          dispatch({ type: 'exam/fetchExamPaperList', payload: { filter: { ref_type: 'examPaper', ref_id } } });
        }
      },
      goToExam(examPaper) {
        dispatch(routerRedux.push(`/examMain?shopId=${examPaper.shopId}&exam_time=${examPaper.exam_time}&ref_type=${examPaper.ref_type}&ref_id=${examPaper._id}&examLibName=` + encodeURIComponent(examPaper.name)));
      },
    };
  },
)(ExamPage);
